<template>
    <div class="goods-box">
      <div class="goods-menu-wrapper"  ref="menu">
      <ul class="menu-box">
        <li class="menu-item" v-for="(item,index) in goods"
            :key="item.id"
            @click="selectMenu(index,$event)"
            :class="{'current':currentIndex === index}">
          <span class="text border-1px">
            <i v-show= "item.type > 0" class="icon" :class="classMap[item.type]"></i>{{item.name}}</span>
        </li>
      </ul>
      </div>
      <div class="goods-products-wrapper" ref="product">
        <ul class="products-box">
          <li class="products-list food-list-hook" v-for="item in goods" :key="item.id" >
            <h1 class="product-title">{{item.name}}</h1>
            <ul>
              <li class="products-list-item border-1px" v-for="food in item.foods" :key="food.id">
               <div class="procuct-item-img">
                 <img :src="food.image" alt="食物图片">
               </div>
                <div class="product-item-content">
                  <h2 class="product-item-name">{{food.name}}</h2>
                  <p class="product-item-desc">{{food.description}}</p>
                  <div class="product-item-extra">
                    <span class="product-item-count">月售{{food.sellCount}}份</span>
                    <span class="product-item-comment">好评率{{food.rating}}%</span>
                  </div>
                  <div class="product-item-price">
                    <span class="current-price-band">￥</span>
                    <span class="current-price">{{food.price}}</span>
                    <span class="old-price-brand" v-if="food.oldPrice > 0">￥</span>
                    <span class="old-price" v-if="food.oldPrice > 0">{{food.oldPrice}}</span>
                  </div>
                  <div class="add-cart-wrapper">
                    <add-cart :food="food"></add-cart>
                  </div>
                </div>
              </li>
            </ul>
          </li>
        </ul>
      </div>
      <shop-cart class="shop-cart-wrapper" :selectFoods="selectFoods" v-if='seller.deliveryPrice'  :deliveryPrice="seller.deliveryPrice" :minPrice="seller.minPrice"></shop-cart>
    </div>
</template>

<!--设计左右联动，坐标的区间，左侧应该高亮效果,就是讲没一个li的高度集中到一个数组里面，根据值去判断滚动到哪里，讲scrollY与listHeight-->
<!--点击左侧，让右边的数据滚动到相应下标的区域，就实现双向关联啦-->

<script>
  import axios from '../../common/js/axiosData'
  import BScroll from 'better-scroll'
  import addCart from '../../components/addcart/addcart'
  import shopCart from '../../components/shopcart/shopcart'
  const ERROR_OK = 0
    export default {
        name: 'goods',
      data () {
          return {
            goods: [],
            seller: [],
            activeIndex: 0, // 当前激活的菜单
            classMap: ['decrease', 'discount', 'special', 'invoice', 'guarantee'],
            listHeight: [], // 每个li的高度
            scrollY: 0 // 滚动的位置
          }
      },
      created () {
        this.getGoods()
        this.getData()
      },
      components: {
        addCart,
        shopCart
      },
      computed: {
          currentIndex () {
            // 不知道为什么下标是从8开始的
            for (let i = 0; i <= this.listHeight.length; i++) {
              let height1 = this.listHeight[i]
              let height2 = this.listHeight[i + 1]
              //  如果是最后一个值，表示已经到i区间啦
              if (!height2 || (this.scrollY >= height1 && this.scrollY < height2)) {
                if (i === this.listHeight.length - 1) {
                  return 0
                }
                 return i + 1
              }
            }
            return 0
          },
          selectFoods () {
            let foods = []
            this.goods.forEach((good) => {
              good.foods.forEach((food) => {
                if (food.count) {
                  foods.push(food)
                }
              })
            })
            return foods
        }
      },
      methods: {
        getGoods () {
          axios.get('/api/goods').then(res => {
            if (res.error === ERROR_OK) {
              this.goods = res.data
              // dom加载完就行
              this.$nextTick(() => {
                // 计算高度
                this._initScroll()
                this._calculHeight()
              })
            }
          })
        },
        getData () {
          axios.get('/api/seller').then(res => {
            if (res.error === ERROR_OK) {
              this.seller = res.data
            }
          })
        },
        selectMenu (index, event) {
         // pc和移动端点击执行两次的解决办法
         //  if (!event._constructed) {
         //      return
         //  }
          // 点击的时候，在哪个下标下面，就滚动到什么位置
          let foodList = this.$refs.product.getElementsByClassName('food-list-hook')
          let el = foodList[index]
          // 滚动到300
          this.foodScroll.scrollToElement(el, 200)
        },
        _initScroll () {
          this.menuScroll = new BScroll(this.$refs.menu, {
            click: true
          })
          this.foodScroll = new BScroll(this.$refs.product, {
            //  这个值可以实时记录滚蛋的位置
            probeType: 3,
            click: true
          })
          this.foodScroll.on('scroll', (pos) => {
            // 判断滑动方向，避免下拉时分类高亮错误（如第一分类商品数量为1时，下拉使得第二分类高亮）
            if (pos.y <= 0) {
              this.scrollY = Math.abs(Math.round(pos.y))
            }
          })
        },
        _calculHeight () { // 计算高度
          let foodList = this.$refs.product.getElementsByClassName('food-list-hook')
          let height = 0
          for (let i = 0; i < foodList.length; i++) {
            let item = foodList[i]
            height += item.clientHeight
            this.listHeight.push(height)
          }
        }
      }
    }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "../../common/stylus/mixin.styl"
  .goods-box
    display: flex
    position: absolute
    left:0
    top:174px
    bottom: 46px
    width: 100%
    overflow: hidden
  .goods-menu-wrapper
    flex:0 0 80px
    width: 80px
    background-color: #f3f5f7
  .menu-box
    .menu-item
      width: 100%
      height: 54px
      padding: 0 12px
      box-sizing: border-box
      font-size: 0
      display: table
      .text
        font-size:12px
        color:#333
        line-height:14px
        border-1px(rgba(7,17,27,.1))
        display: table-cell;
        vertical-align: middle;
        position: relative
      &:last-child
        .text
          border-none()
          margin-bottom: 0
      &.current
        position:relative
        background: #ffffff
        z-index:10
        margin-top:-1px
        .text
          border-none()
      .icon
        display: inline-block
        vertical-align: top
        width: 12px
        height: 12px
        margin-right: 2px
        background-repeat: no-repeat
        &.decrease
          background:url("../../../resource/img/decrease_3@2x.png")
          background-size: 100% 100%
        &.discount
          background:url("../../../resource/img/discount_3@2x.png")
          background-size: 100% 100%
        &.guarantee
          background:url("../../../resource/img/guarantee_3@2x.png")
          background-size: 100% 100%
        &.invoice
          background:url("../../../resource/img/invoice_3@2x.png")
          background-size: 100% 100%
        &.special
          background:url("../../../resource/img/special_3@2x.png")
          background-size: 100% 100%
  .products-list-item
    display:flex
    border-1px(rgba(7,17,27,.1))
    &:last-child
      border-none()
      margin-bottom: 0
  .product-item-content
    flex:1
    .product-item-name
      font-size:14px
      color:rgb(7,17,27)
      line-height: 14px
      margin-top:2px
    .product-item-desc,.product-item-extra
      margin-top:8px
      font-size:12px
      color:rgb(147,153,159)
      line-height:12px
    .product-item-price
      font-size:0
      color:#f01414
      margin-top:2px
      .current-price
        font-size:14px
        font-weight:500
        line-height:24px
      .current-price-band
        font-size:12px
      .old-price-brand,.old-price
        font-size:12px
        color:rgb(147,153,159)
        text-decoration:line-through
      .old-price
        font-weight:500
      .old-price-brand
        margin-left:2px
  .product-title
    padding-left:14px
    height:26px
    color: #93999f
    line-height:26px
    background-color: #f3f5f7
    font-size:12px
    border-left:2px solid #d9dde1
  .procuct-item-img
    flex: 0 0 58px
    width:58px
    height:58px
    border-radius:4px
    margin-right:10px
    img
      width: 100%
      height:100%
  .products-list-item
    position:relative
    margin:18px
    padding-bottom:18px
  .add-cart-wrapper
    position:absolute
    bottom:12px
    right:0

</style>
